package com.sanley.coronavirus.service.iml;

import com.github.pagehelper.PageHelper;
import com.sanley.coronavirus.bo.UserBO;
import com.sanley.coronavirus.dao.AuthenticationDao;
import com.sanley.coronavirus.dao.BaseDao;
import com.sanley.coronavirus.dao.UserDao;
import com.sanley.coronavirus.entity.Base;
import com.sanley.coronavirus.entity.User;
import com.sanley.coronavirus.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class UserServiceImp implements UserService {
    @Autowired
    private UserDao dao;

    @Autowired
    private BaseDao baseDao;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private AuthenticationDao authenticationDao;


    @Override
    public User findByUsername(String username) {
        return dao.findByUsername(username);
    }

    @Override
    public void addUser(User user) {
        dao.addUser(user);
    }

    @Override
    public void deleteUser(int id) {
        dao.deleteUser(id);
    }

    @Override
    public List<User> findAll(int page, int size, String keyword) {
        PageHelper.startPage(page, size);
        List<User> all = dao.findAll(keyword);
        return all;
    }

    @Override
    public void addUserRole(int id) {
        dao.addUserRole(id);
    }

    @Override
    public void addAdminRole(int id) {
        dao.addAdminRole(id);
    }

    @Override
    public Boolean logout(String username) {
        try {
            redisTemplate.delete(Arrays.asList("token:" + username, "authorities:" + username));
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    @Override
    public Boolean addOneUser(UserBO userBO) {
        String s = dao.selectNameByUsername(userBO.getUsername());
        if (s != null) {
            return false;
        }
        User user = new User();
        Base base = new Base();
        BeanUtils.copyProperties(userBO, user);
        BeanUtils.copyProperties(userBO, base);
        baseDao.add(base);
        user.setBaseId(base.getId());
        dao.addOneUser(user);
        dao.addUserRole(user.getId());
        return true;
    }

    @Override
    public User getUserInfo(String username) {
        return dao.selectUserInfoByUsername(username);
    }

    @Override
    public List<SimpleGrantedAuthority> getAuthorityByUsername(String username) {

        List<SimpleGrantedAuthority> authorities = (List<SimpleGrantedAuthority>) redisTemplate.opsForValue().get("authorities:" + username);
        if (authorities == null) {
            authorities = authenticationDao.getAuthorityByUsername(username);
        }
        return authorities;
    }
}
